var modifyOrAddFlag;

$(document).ready(function(){

	$('#win').window('close');
	$(".button_con a" ).removeClass("l-btn-plain");
	
	$("#toolbar_add").click(function(e) {
		 $('#addForm')[0].reset();
	});
	



		
		//DBLink数据库链接管理表格
		var randomNu = (new Date().getTime()) ^ Math.random();
		$("#datagrid").datagrid({
			url : BASE_URL_DBLINK_DATA_SOURCE_SEARCH +'/findByExample'  + '?v=' + Math.random() ,
			method:'get',
			autoRowHeight:true,
			nowrap:false,
			pageSize:20,
			singleSelect:true,
			striped:true,
			pageList:[10,20,50,100],
			columns:[[
						{field:'',width:10,checkbox:true},
						{field:'name',title:'数据库链接名称',width:150,align:'left'},
						{field:'host',title:"主机",width:100},
						{field:'dbname',title:'数据库名称',width:100,align:'left'},
						{field:'user',title:'用户名',width:100,align:'left'},
						{field:'port',title:'端口',width:100}
			      ]],
			pagination:true,
			onSelect:function(rowIndex,rowData){
				$("#toolbar_edit").linkbutton('enable');
				$("#toolbar_delete").linkbutton('enable');
			},
			loadFilter:function(data){
				return {
					total: data.totalElements,
					rows: data.content
				};
			},
			onBeforeLoad:function(param){
				param.page -= 1;
				param.size = param.rows;
				delete param.rows;
				param.sort = 'createTime,desc';
				param.name = $('#txtSearchDatabaseLinkName').val();
				param.dbname = $('#txtSearchDatabaseName').val();
			}
		});
		
		$("#datagrid").datagrid('getPager').pagination({   
		    displayMsg:'当前显示从 [{from}] 到 [{to}] 共[{total}]条记录'
		}); 
		
		

});
	//进入新增界面	
	function add(){
		$("#win").window('setTitle','DBLINK数据库链接管理-新增');
		modifyOrAddFlag = true;
		$('#addForm')[0].reset();
		$("#addForm").form("validate");
		$('#win').window('open');
	}
	//进入修改界面
	function update(){
		$("#win").window('setTitle','DBLINK数据库连接管理-修改');
		modifyOrAddFlag = false;
		var row = $('#datagrid').datagrid('getSelected');
		if(row == null){
			$.messager.alert("警告","<p>请选中要修改的记录！</p>","warning");	
		}else{
			$("#txtDatabaseLinkName").val(row.name);
			$("#hostcomputer").val(row.host);
			$("#txtDatabaseName").val(row.dbname);
			$("#txtUserName").val(row.user);
			$("#txtUserPass").val(row.password);
			$("#txtPort").val(row.port);
			$("#addForm").form("validate");
			$('#win').window('open');
		}
	}
	
	
	//删除
	function del(){
		var row = $('#datagrid').datagrid('getSelected');
		if(row == null){
			$.messager.alert("警告","<p>请选中要删除的记录!</p>","warning");
		}else{
			if (row){
			$.messager.confirm('温馨提示','<p>你真的要删除么?</p>',function(result){
				if (result){
			 		$.ajax({
						url: BASE_URL_DBLINK_DATA_SOURCE_CRUD + '/' + row.id + '?v=' + Math.random(),
						dataType:'json',
						type:'delete',
						async:false,
						contentType:"application/json",
						timeout:30000,
						success:function(){
							$.messager.alert("提示","<p>删除成功！</p>","info");	
							$("#datagrid").datagrid("reload", BASE_URL_DBLINK_DATA_SOURCE_SEARCH + '/findByExample' + '?v=' + Math.random());
						},
						error:function(xhr,s,err){
							$.messager.alert("错误","<p>服务异常，删除数据库链接失败，请重新登录或稍后重试！</p>","error");	
						}
			 		});
				}
			});
		}
		}
	}
	function rePage(){
		$('#win').window('close');
		$("#datagrid").datagrid("reload", BASE_URL_DBLINK_DATA_SOURCE_SEARCH +'/findByExample'  + '?v=' + Math.random());
	}
	
	//保存
	function onSave(){
		var row = $('#datagrid').datagrid('getSelected');
		var name=$("#txtDatabaseLinkName").val();
		var host=$("#hostcomputer").val();
		var dbname=$("#txtDatabaseName").val();
		var user=$("#txtUserName").val();
		var password=$("#txtUserPass").val();
		var port=$("#txtPort").val();
		jsonData = JSON.stringify({name:name,host:host,dbname:dbname,user:user,password:password,port:port});
		var jsonStr = JSON.stringify(jsonData);
		if($("#addForm").form("validate")){
			$("#instance_save").linkbutton("disable");
			$("#instance_save .l-btn-text").text("提交中...");
	 		if(!modifyOrAddFlag){
	 			//名字发生变更，则校验名字是否可用
	 			if(name != row.name || host != row.host)
	 			{
	 				var checkParam = {
	 						name:$("#txtDatabaseLinkName").val(), 
	 						host:$("#hostcomputer").val(),
	 						originalId:row.id
 						};
	 				$.ajax({
						url:BASE_URL_DBLINK_DATA_SOURCE_SEARCH +'/checkIsCanSave' + '?v=' + Math.random(),
						dataType:'json',
						type:'get',
						contentType:"application/json",
						data: checkParam,
						success:function(data){
							if(!data.isCanSave){
								$("#instance_save").linkbutton("enable");
								$("#instance_save .l-btn-text").text("保存");
								$.messager.alert('错误','<p>数据库链接名称或主机已存在，请使用其他名称</p>','error');
							}else{
								modifyOne(jsonStr);
							}
						},
						error: function() {
							$.messager.alert("错误","<p>服务异常，修改数据库链接信息失败，请重新登录或稍后再试！</p>","error");	
							$("#instance_save").linkbutton("enable");
							$("#instance_save .l-btn-text").text("保存");
						}
		 			});
	 			}else{
	 				modifyOne(jsonStr);
	 			}
	 		}else{
	 			var checkParam = {
						name:$("#txtDatabaseLinkName").val(), 
 						host:$("#hostcomputer").val()
					};
 				$.ajax({
					url:BASE_URL_DBLINK_DATA_SOURCE_SEARCH +'/checkIsCanSave' + '?v=' + Math.random(),
					dataType:'json',
					type:'get',
					contentType:"application/json",
					data: checkParam,
					success:function(data){
						if(!data.isCanSave){
							$("#instance_save").linkbutton("enable");
							$("#instance_save .l-btn-text").text("保存");
							$.messager.alert('错误','<p>' + data.reason + '</p>','error');
						}else{
							addOne(jsonStr);
						}
					},
					error: function() {
						$.messager.alert("错误","<p>服务异常，新增数据库链接失败，请重新登录或稍后再试！</p>","error");	
						$("#instance_save").linkbutton("enable");
						$("#instance_save .l-btn-text").text("保存");
					}
	 			});
	 		}
		}
	}
	//新增
	function addOne(jsonStr) {
		if(!jsonStr)
		{
			var row = $('#datagrid').datagrid('getSelected');
			var name=$("#txtDatabaseLinkName").val();
			var host=$("#hostcomputer").val();
			var dbname=$("#txtDatabaseName").val();
			var user=$("#txtUserName").val();
			var password=$("#txtUserPass").val();
			var port=$("#txtPort").val();
			jsonData = JSON.stringify({name:name,host:host,dbname:dbname,user:user,password:password,port:port});
			jsonStr = JSON.stringify(jsonData);
		}
		
		$.ajax({
			url: BASE_URL_DBLINK_DATA_SOURCE_CRUD,
			type:'post',
			contentType:"application/json",
			data:jsonData,
			success:function(){
				$.messager.alert("提示","<p>新增成功！</p>","info");
				$('#win').window('close');
				$("#datagrid").datagrid("reload", BASE_URL_DBLINK_DATA_SOURCE_SEARCH + '/findByExample' + '?v=' + Math.random());
				$("#instance_save").linkbutton("enable");
				$("#instance_save .l-btn-text").text("保存");
			},
			error:function(){
				$.messager.alert("错误","<p>服务异常，新增数据库链接失败，请重新登录或稍后再试！</p>","error");	
				$("#instance_save").linkbutton("enable");
				$("#instance_save .l-btn-text").text("保存");
			}
		});
	}
	//修改
	function modifyOne(jsonStr) {
		var row = $('#datagrid').datagrid('getSelected');
		if(!jsonStr)
		{
			var name=$("#txtDatabaseLinkName").val();
			var host=$("#hostcomputer").val();
			var dbname=$("#txtDatabaseName").val();
			var user=$("#txtUserName").val();
			var password=$("#txtUserPass").val();
			var port=$("#txtPort").val();
			jsonData = JSON.stringify({name:name,host:host,dbname:dbname,user:user,password:password,port:port});
			jsonStr = JSON.stringify(jsonData);
		}
		
		$.ajax({
				url: BASE_URL_DBLINK_DATA_SOURCE_CRUD + '/' + row.id + '?v=' + Math.random(),
				type:'put',
				contentType:"application/json",
				data:jsonData,
				success:function(){
					$.messager.alert("提示","<p>修改成功！</p>","info");	
					$('#win').window('close');
					$("#datagrid").datagrid("reload", BASE_URL_DBLINK_DATA_SOURCE_SEARCH + '/findByExample' + '?v=' + Math.random());
					$("#instance_save").linkbutton("enable");
					$("#instance_save .l-btn-text").text("保存");
				},
				error:function(){
					$.messager.alert("错误","<p>服务异常，修改数据库链接信息失败，请重新登录或稍后再试！</p>","error");	
					$("#instance_save").linkbutton("enable");
					$("#instance_save .l-btn-text").text("保存");
				}
			});
	}
	//查询
	function search(){
		$("#datagrid").datagrid("reload", BASE_URL_DBLINK_DATA_SOURCE_SEARCH + '/findByExample' + '?v=' + Math.random());
	}